// pages/stats/stats.js
// 引入图表工具
const { LearningTrendChart } = require('../../utils/chart');

Page({
  data: {
    totalWords: 0,
    masteredWords: 0,
    reviewWords: 0,
    errorWords: 0,
    learningTrend: [],
    errorWordsList: [],
    timeRange: 'week', // 'day', 'week', 'month'
    chartInstance: null
  },

  // 切换时间范围
  switchTimeRange(e) {
    const timeRange = e.currentTarget.dataset.range
    this.setData({
      timeRange
    })
    this.fetchLearningTrend()
  },

  // 获取学习趋势数据
  fetchLearningTrend() {
    const { timeRange, chartInstance } = this.data
    // 模拟学习趋势数据
    let labels = []
    let data = []
    let title = ''

    if (timeRange === 'day') {
      labels = ['08:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00']
      data = [10, 15, 5, 20, 15, 25, 30]
      title = '今日学习趋势'
    } else if (timeRange === 'week') {
      labels = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      data = [50, 70, 60, 90, 80, 120, 100]
      title = '本周学习趋势'
    } else {
      labels = ['1月', '2月', '3月', '4月', '5月', '6月']
      data = [300, 450, 600, 800, 1000, 1200]
      title = '本月学习趋势'
    }

    this.setData({
      learningTrend: {
        labels,
        data
      }
    })

    // 更新图表数据
    if (chartInstance) {
      chartInstance.updateData({
        labels,
        data,
        title
      });
    }
  },

  // 初始化图表
  initChart() {
    const chartInstance = new LearningTrendChart('learningTrendChart', {
      width: 300,
      height: 200,
      labels: this.data.learningTrend.labels || [],
      data: this.data.learningTrend.data || [],
      title: this.data.timeRange === 'day' ? '今日学习趋势' : this.data.timeRange === 'week' ? '本周学习趋势' : '本月学习趋势',
      lineColor: '#3b82f6',
      fillColor: 'rgba(59, 130, 246, 0.1)'
    });

    this.setData({
      chartInstance
    });
  },

  // 查看全部常错单词
  viewAllErrorWords() {
    wx.navigateTo({
      url: '/pages/errorWords/errorWords'
    })
  },

  onLoad: function () {
    // 模拟统计数据
    this.setData({
      totalWords: 246,
      masteredWords: 189,
      reviewWords: 57,
      errorWords: 42,
      errorWordsList: [
        {
          id: 1,
          word: 'ambiguous',
          definition: 'adj. 模棱两可的',
          errorCount: 3
        },
        {
          id: 2,
          word: 'consequence',
          definition: 'n. 结果，后果',
          errorCount: 2
        },
        {
          id: 3,
          word: 'elaborate',
          definition: 'adj. 详尽的；v. 详细说明',
          errorCount: 2
        }
      ]
    })

    // 获取学习趋势数据
    this.fetchLearningTrend()

    // 延迟初始化图表，确保canvas已经渲染
    setTimeout(() => {
      this.initChart();
    }, 100);
  }
})